package org.example.servlet;

import org.example.util.FileDownloadUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * 文件服务Servlet
 */
public class FileServiceServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain;charset=UTF-8");
        
        String pathInfo = request.getPathInfo();
        
        if (pathInfo == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        if ("/down.do".equals(pathInfo)) {
            handleDownload(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
    
    /**
     * 处理文件下载请求
     */
    private void handleDownload(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        
        String fileUrl = request.getParameter("url");
        
        if (fileUrl == null || fileUrl.trim().isEmpty()) {
            response.getWriter().print("错误：缺少url参数");
            return;
        }
        
        try {
            // 构建服务器基础URL
            String serverBaseUrl = request.getScheme() + "://" + 
                                  request.getServerName() + ":" + 
                                  request.getServerPort() + 
                                  request.getContextPath();
            
            // 执行多线程下载
            String downloadUrl = FileDownloadUtil.downloadFile(fileUrl, serverBaseUrl);
            
            // 返回下载地址
            response.getWriter().print(downloadUrl);
            
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().print("下载失败：" + e.getMessage());
        }
    }
}
